import { onMounted, reactive, Ref, ref } from 'vue';
import { PageQuery } from '@/api';
import { QueryForm } from '@/components/query-form';
import type { ComponentSize } from 'element-plus';

export type pages = {
  page_num: number;
  page_size: number;
  curr_size: number;
  total_count: number;
};

export default function useTable(fetchDataList: Function,
                                 formRef?: Ref<InstanceType<typeof QueryForm> | undefined>,
                                 formResetAutoLoad = true,
                                 immediate = true,
                                 pageSize = 10,
) {
  const size = ref<ComponentSize>('default');
  const pageSizes = ref<number[]>([5, 10, 15, 30, 50, 100])
  const stripe = ref(true);
  const showQueryForm = ref(true);
  const pageQuery = reactive<PageQuery>({
    pageNum: 1,
    pageSize: pageSize,
    orderMode: undefined,
    orderColumn: undefined,
  });

  onMounted(() => {
    // 是否初始化的时候请求一次
    if (immediate) {
      fetchDataList?.();
    }
  })

  const methods = {
    handleSizeChange: async (val: number) => {
      pageQuery.pageSize = val;
      fetchDataList?.();
    },
    handleCurrentChange: async (val: number) => {
      pageQuery.pageNum = val;
      fetchDataList?.();
    },
    handleSortChange: (data: { column: any, prop: string, order: any }) => {
      if (data.order !== pageQuery.orderMode || data.prop !== pageQuery.orderColumn) {
        pageQuery.orderMode = data.order === 'ascending' ? 'ASC' : 'DESC'
        pageQuery.orderColumn = data.prop
        fetchDataList?.();
      }
    },
    handleResetForm: async () => {
      if (!formRef?.value?.formRef) return;
      formRef?.value?.formRef.resetFields();
      if (formResetAutoLoad) {
        pageQuery.pageNum = 1;
        pageQuery.pageSize = pageSize;
        pageQuery.orderMode = undefined;
        pageQuery.orderColumn = undefined;
        fetchDataList?.();
      }
    },
  }

  return {
    tableState: {
      size,
      stripe,
      showQueryForm,
      pageQuery,
      pageSizes
    },
    tableMethods: methods
  };
}
